import { Modal } from 'antd';
import _ from 'lodash';
import stores from '@redux/stores.js';
import * as Api from '@api/nodes';
const { confirm } = Modal;

const getState = () => {
  const state = stores?.getState();
  let hasCluster = _.get(state, 'auth.cert.is_cluster', false);
  let isCluster = _.includes(state?.auth?.cert?.modules, 'distribute');
  return { hasCluster, isCluster };
};
const apiError = (error, reject) => {
  let error_code = _.get(error, 'response.data.error_code.status');
  // 如果是集群设备但是没有节点
  if (error_code === 'fail') {
    confirm({
      title: '当前无可用扫描节点,请联系系统管理员添加扫描节点',
      okText: '确定',
      cancelText: '取消',
      width: '500px',
      onOk() {},
      onCancel() {}
    });
  }
  reject();
};

const isClusterModel = () => {
  return new Promise(async (resolve, reject) => {
    const { hasCluster, isCluster } = getState();
    if (!hasCluster && !isCluster) {
      resolve();
      return;
    }
    // 是集群有扫描节点要请求判断接口
    await Api.getConnectedNodes()
      .then(() => resolve())
      .catch(e => apiError(e, reject));
  });
};

export default isClusterModel;
